<template>
  <div class="tinymce-editor">
    <editor
      ref="tinymce"
      id="tinymce"
      v-if="!reloading"
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick">
    </editor>
  </div>
</template>

<script>
  import tinymce from 'tinymce/tinymce'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/themes/silver/theme'
  import 'tinymce/plugins/image'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/media'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/contextmenu'
  import 'tinymce/plugins/wordcount'
  import 'tinymce/plugins/colorpicker'
  import 'tinymce/plugins/textcolor'
  import 'tinymce/plugins/fullscreen'
  import 'tinymce/icons/default'
  import { getVmParentByName } from '@/utils/util'
  import axios from 'axios'
  import { getAccessToken } from "@/utils/auth";
  export default {
    components: {
      Editor
    },
    props: {
      value: {
        type: String,
        required:false
      },
      triggerChange:{
        type: Boolean,
        default: false,
        required:false
      },
      disabled: {
        type: Boolean,
        default: false
      },
      height: {
        type: Number,
        default: 300
      },
      plugins: {
        type: [String, Array],
        default: 'lists image link media table textcolor wordcount contextmenu fullscreen '
      },
      toolbar: {
        type: [String, Array],
        default: 'undo redo |  formatselect | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists  image media table |  fontselect fontsizeselect forecolor backcolor  removeformat  | fullscreen  lineheight| clean | addTableClass  ',
        branding:false
      }
    },
    data() {
      return {
        //初始化配置
        init: {
          language_url: '/tinymce/langs/zh_CN.js',
          language: 'zh_CN',
          skin_url: '/tinymce/skins/lightgray',
          height: this.height,
          plugins: this.plugins,
          toolbar: this.toolbar,
          branding: false,
          menubar: false,
          toolbar_drawer: false,
          relative_urls : false,
          convert_urls: false,
          // forced_root_block: false,
          table_default_attributes: {
              width: '95%'       // 设置表格宽度为100%
          },
          lineheight_formats :'0 0.5 1 1.5 2',
          fontsize_formats:'8pt 9pt 9.5pt 10pt 10.5pt 11pt 12pt 13pt 14pt 18pt 24pt 36pt ',
          font_formats:"微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
          images_upload_handler: (blobInfo, success) => {
            let formData = new FormData()
            formData.append('file', blobInfo.blob(), blobInfo.filename());

            axios({
              method: 'post',
              url: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload",
              headers: { 
                'Authorization': 'Bearer ' + getAccessToken(),
                'Content-Type': 'multipart/form-data',  // 文件上传
              },
              data:formData
            }).then((res) => {
              if (res.data.code==0) {
                success(res.data.data)
              }
            })

            // uploadAction(process.env.VUE_APP_BASE_API + "/common/upload", formData).then((res) => {
            //   if (res.code==200) {
            //       success(res.url)
            //     // if(res.message == 'local'){
            //     //   // const img = 'data:image/jpeg;base64,' + blobInfo.base64()
            //     //   // success(img)
            //     //   success(res)
            //     // }else{
            //     //   let img = getFileAccessHttpUrl(res.message)
            //     //   success(img)
            //     // }
            //   }
            // })
          },
          setup(editor) {  
            editor.ui.registry.addButton('clean', {  
              text: 'clean',  
              onAction: () => {  
                const selectedContent = editor.selection.getContent();  
                if (selectedContent) {  
                  // Wrap selected content in a div with margin style  
                  const marginStyle = 'margin: -1em 0;display: block;'; // You can make this dynamic based on user input  
                  const wrappedContent = `<span style="${marginStyle}">${selectedContent}</span>`;  
                    
                  // Insert the wrapped content at the current selection  
                  editor.insertContent(wrappedContent);  
                } else {  
                  // Handle the case where no text is selected  
                  // alert('Please select some text to set margin.');  
                }  
              },  
            });  
            editor.ui.registry.addButton('addTableClass', {
                text: '表格不分页',
                onAction: function () {
                    var table = editor.dom.getParent(editor.selection.getNode(), 'table');
                    if (table) {
                        editor.dom.addClass(table, 'table-no-pagination'); // 替换为您的 class 名称
                    } else {
                        alert('Please select a table first!');
                    }
                }
            });
          },  
        },
        myValue: this.value,
        reloading: false,
      }
    },
    mounted() {
      this.initATabsChangeAutoReload()
    },
    methods: {

      reload() {
        this.reloading = true
        this.$nextTick(() => this.reloading = false)
      },

      onClick(e) {
        this.$emit('onClick', e, tinymce)
      },
      //可以添加一些自己的自定义事件，如清空内容
      clear() {
        this.myValue = ''
      },

      /**
       * 自动判断父级是否是 <a-tabs/> 组件，然后添加事件监听，自动触发reload()
       *
       * 由于 tabs 组件切换会导致 tinymce 无法输入，
       * 只有重新加载才能使用（无论是vue版的还是jQuery版tinymce都有这个通病）
       */
      initATabsChangeAutoReload() {
        // 获取父级
        let tabs = getVmParentByName(this, 'ATabs')
        let tabPane = getVmParentByName(this, 'ATabPane')
        if (tabs && tabPane) {
          // 用户自定义的 key
          let currentKey = tabPane.$vnode.key
          // 添加事件监听
          tabs.$on('change', (key) => {
            // 切换到自己时执行reload
            if (currentKey === key) {
              this.reload()
            }
          })
        }else{
          //update--begin--autor:wangshuai-----date:20200724------for：富文本编辑器切换tab无法修改------
          this.reload()
          //update--begin--autor:wangshuai-----date:20200724------for：文本编辑器切换tab无法修改------
        }
      },

    },
    watch: {
      value(newValue) {
        this.myValue = (newValue == null ? '' : newValue)
      },
      myValue(newValue) {
        if(this.triggerChange){
          this.$emit('change', newValue)
        }else{
          this.$emit('input', newValue)
        }
      }
    }
  }

</script>
<style >
	/* 在el-dialog中tinymce z-index 被太小而被遮挡时要加这两句 */
	.tox-tinymce-aux{z-index:99999 !important;}
	.tinymce.ui.FloatPanel{z-Index: 99;}
</style>